import cookie from 'react-cookies';
import {  Message} from '@knownsec/react-component';

const baseUrl = '/api/v1';
/**
 *
 * 请求封装
 */
export default function Fetch({
  url,
  method = 'GET',
  data = {},
  file,
  blob,
  isheaders = true,
  getHeader = false,
  refre=true
}) {
  let u;
  let body;
  let contentType;
  if (!file) {
    u =
      baseUrl +
      url +
      (method === 'GET' && data && Object.keys(data).length > 0
        ? '?' + json2params(data) + ''
        : '');
    body =
      method === 'GET'
        ? {}
        : {
          body: JSON.stringify(data),
        };
    contentType = { 'Content-Type': 'application/json;charset=UTF-8' };
  } else {
    u = baseUrl + url;
    body = { body: data };
    contentType = {};
  }
  let hd;
  if (isheaders) {
    hd = {
      ...contentType,
    };
    let token = cookie.load('token');
    if (token) {
      hd.AUTHORIZATION = 'Bearer ' + cookie.load('token');
    }
  } else {
    hd = {
      ...contentType,
    };
  }
  return fetch(u, {
    method,
    headers: hd,
    ...body,
    ...blob,
  })
    .then((res) => {
      if (res.status === 401) {
        return res.json().then(res => {
          if (res.errcode === '40000401') {
            window.location.href = '/#/upcert'
          }else if (res.errcode === '40001401') {
            window.location.href = '/#/login'
            cookie.save('refresh', '')
            cookie.save('token', '')
            cookie.save('username', '')
          } else {
            if (!cookie.load('refresh')) {
              window.location.href = '/#/login'
              cookie.save('refresh', '')
              cookie.save('token', '')
              cookie.save('username', '')
              return Promise.reject(url === '/account/login/' ? '登录用户名或密码不正确' : '登录过期')
            }
            if (refre) {
              return refreshToken().then(res => {
                cookie.save('token', '')
                cookie.save('refresh', res.data.refresh)
                cookie.save('token', res.data.token)
                return Fetch({ url, method, data, file, blob, refre: false })
              })
            }
          }
        })
      } else {
        if (blob) {
          return res.blob().then((blob) => {
            if (res.ok) {
              const con = res.headers.get('content-disposition') || '';
              const idx = con.indexOf('=');
              const fileName = decodeURI(con.substring(idx + 1));
              return saveBlobAs(blob, fileName);
            } else {
              const err = res.status === 500 ? '系统错误' : res.status === 403 ? '暂无权限' : blob;
              return Promise.reject(err);
            }
          });
        }
        return res.json().then((json) => {
          if(json.errcode==='40301403'){
            Message.show({
              pro: true,
              showClose: false,
              type: 'success',
              message: json.message||'',
            });
            return json;
          }
          if(Object.prototype.toString.call(json.message)==='[object Object]'){
            if (Object.values(json.message)[0].toLowerCase().indexOf('token') > -1) {
              if (!cookie.load('refresh')) return Promise.reject('登录用户名或密码不正确');
              return refreshToken().then((res) => {
                cookie.save('token', res.data.token);
                return Fetch({ url, method, data, file, blob });
              });
            }
          }
          if (res.ok) {
            if (getHeader) {
              json.req_header = res.headers;
              return json;
            } else {
              return json;
            }
          } else {
            const err = res.status === 500 ? '系统错误' : res.status === 403 ? '暂无权限' : json;
            return Promise.reject(err);
          }
        });
      }
    })
    .catch((error) => {
      console.log('error is', error);
      return Promise.reject(error);
    });
}
function saveBlobAs(blob, text) {
  const anchor = document.createElement('a');
  const body = document.querySelector('body');
  anchor.href = window.URL.createObjectURL(blob);
  anchor.download = text;
  anchor.style.display = 'none';
  body.appendChild(anchor);
  anchor.click();
  body.removeChild(anchor);
  window.URL.revokeObjectURL(anchor.href);
}

function refreshToken() {
  return fetch('/api/v1/account/refresh/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
    },
    body: JSON.stringify({
      refresh: cookie.load('refresh'),
    }),
  }).then((res) => {
    return res.json().then((json) => {
      if (json.status === 'fail') {
        window.location.href = '/#/login';
        cookie.save('refresh', '');
        cookie.save('token', '');
        cookie.save('username', '');
        return Promise.reject('登录过期');
      } else {
        return json;
      }
    });
  });
}

function json2params(json, slice = '&') {
  return Object.keys(json)
    .reduce((acc, item) => {
      return String(acc) + item + '=' + json[item] + slice;
    }, '')
    .slice(0, -1);
}
